package com.yang.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yang.dao.BaseDAO;
import com.yang.entity.User;
import com.yang.model.Page;
import com.yang.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private BaseDAO<User> baseDao;

	public User getById(String id) {
		List<User> list = baseDao.find("from User where id=1");
		if (list != null) {
			return list.get(0);
		}
		return null;
	}

	public User getByUserName(String username) {
		String hql = "from User where username=?";
		Object[] params = new Object[] { username };
		List<User> userList = baseDao.find(hql, params);
		if (userList != null && userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	public Page<User> getUserPage(String nowPage, String pageSize) {
		String hql = "from User";
		Integer pageNo = pasrePageNow(nowPage);
		Integer pageSizeInt = Integer.parseInt(pageSize);
		
		List<User> users = baseDao.find(hql, new Object[] {}, pageNo, pageSizeInt);
		long totalCount = baseDao.count(hql);

		Page<User> page = new Page<User>(pageSizeInt);
		page.setTotalCount(totalCount);
		page.setResult(users);
		page.setPageNo(pageNo);
		return page;
	}
	
	/**
	 * 转化前端传来的当前页
	 * @param nowPage	当前页
	 * @return
	 */
	private Integer pasrePageNow(String nowPage){
		if(null!=nowPage){
			Integer pageNo = Integer.parseInt(nowPage);
			return pageNo;
		}
		return 1;
	}

	public void addMoreUser() {
		/*for (int i = 0; i < 326; i++) {
			User u = new User();
			u.setNickname("test"+i);
			u.setUsername("Test"+i);
			u.setEmail("aaa@qq.com");
			u.setPassword("123456");
			baseDao.save(u);
		}*/
	}

}
